package org.example.huawei;

import java.util.Arrays;

/**
 * @author Yyming
 * @version 10.0
 * Created by Yyming on 2021/3/30
 */
public class Test330 {

    public static void main(String[] args) {
        System.out.println(subtract("543215423", "123412431"));
        System.out.println(subtract("1000", "998"));
        System.out.println(subtract("1000", "888"));
        System.out.println(subtract("1000", "8"));

    }


    public static String subtract(String a, String b) {
        int max = Math.max(a.length(), b.length());
        char[] aArray = a.toCharArray();
        char[] bArray = b.toCharArray();
        char[] result = new char[max];

        int indexA = aArray.length - 1;
        int indexB = bArray.length - 1;
        int indexR = max - 1;
        while (indexB >= 0) {
            char aChar = aArray[indexA];
            char bChar = bArray[indexB];
            if (aChar >= bChar) {
                result[indexR] = String.valueOf(aChar - bChar).charAt(0);
            } else {
                //不够,向前借,排了序,必定能借到
                result[indexR] = String.valueOf(aChar - bChar + 10).charAt(0);
                int j = indexA;
                boolean stop = true;
                while (stop) {
                    j--;
                    char before = aArray[j];
                    if (before == '0') {
                        aArray[j] = '9';
                        //需要继续向前借
                    } else {
                        //不是0就 -1
                        aArray[j] = String.valueOf(before - '1').charAt(0);

                        stop = false;
                    }
                }
            }
            indexA--;
            indexB--;
            indexR--;
        }
        if (indexA >= 0 ) {
            //超过的部分补一下
            System.arraycopy(aArray, 0, result, 0, indexA + 1);
        }

        return new String(result).trim();
    }

}
